<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               ref="crud"
               v-model="form"
               :defaults.sync="showColumn"
               :permission="permissionList"
               :page.sync="page"
               :before-open="beforeOpen"
               @sortable-change="cloumnSaveOrUpdate"
               @row-del="rowDel"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @refresh-change="refreshChange"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @filter="filterChange"
               @sort-change="sortChange"
               @row-dblclick="handleRowDBLClick"
               @on-load="onLoad">

      <template slot-scope="scope" slot="menu">
        <el-button type="text"
                   size="small"
                   icon="el-icon-document-copy"
                   v-if="permission.database_delete"
                   @click="handleCopy(scope.row)">复 制
        </el-button>
        <el-button type="text"
                   size="small"
                   icon="el-icon-document-copy"
                   v-if="permission.database_edit"
                   @click.stop="handleOpenColumn(scope.row)">代 码
        </el-button>
      </template>
      <template slot-scope="scope" slot="menuLeft"> 
        <el-button type="danger"
                   size="small"
                   icon="el-icon-delete"
                   v-if="permission.database_delete"
                   @click="handleDelete">删 除
        </el-button> 
      </template> 
      <template slot="menuRight">
        <el-button type="default" @click.stop="exportExcel" icon="el-icon-download" circle size="small"></el-button>
      </template>
    </avue-crud>
    <el-drawer
        :title="drawerTitle"
        :visible.sync="drawerDialog"
        :before-close="handleClose"
        custom-class="demo-drawer"
        destroy-on-close="true"
        ref="drawer"
        direction="rtl"
        size="100%"
        @close="closeDrawer"
        >
        <el-divider></el-divider> 
        <avue-crud  :option="columnOption" 
                    :data="columnData"
                    ref="columnCrud"
                    v-model="columnForm"
                    :permission="permissionList"
                    :page.sync="columnPage"
                    :before-open="beforeOpen"
                    @row-update="cloumnAddUpdate"
                    @row-del="cloumnRowDel"
                    @refresh-change="cloumnRefreshChange"
                    @sortable-change="cloumnSaveOrUpdate"
                    @row-click="selectCurrentRow"
                    @selection-change="columnSelectionChange"
                    >
          <template slot="menuLeft">
            <el-button @click="cloumnAddRow" 
                      icon="el-icon-circle-plus-outline" 
                      type="primary" 
                      size="small">新增字段
            </el-button>
            <el-button type="primary"
                      size="small"
                      icon="el-icon-save"
                      v-if="permission.database_delete"
                      @click="cloumnBatchAdd">批量添加字段
            </el-button>
            <el-button type="primary"
                      size="small"
                      icon="el-icon-save"
                      v-if="permission.database_delete"
                      @click="cloumnBatchEdit">批量编辑
            </el-button>
            <el-button type="primary"
                      size="small"
                      icon="el-icon-save"
                      v-if="permission.database_delete"
                      @click="cloumnSaveOrUpdate">批量保存
            </el-button>

            <el-button size="small" 
                      type="primary" 
                      id="copyBtn" 
                      @click="openPathDialog" 
                      data-clipboard-target="#pathText">路径脚本
            </el-button>
            <el-button size="small" 
                      type="primary" 
                      id="copyBtn" 
                      @click="openPathDialog" 
                      data-clipboard-target="#pathText">ER图
            </el-button>
            <el-button type="warning"
                      size="small"
                      icon="el-icon-edit"
                      v-if="permission.database_delete"
                      @click="generatorSQL()">生成SQL
            </el-button>
            <el-button type="warning"
                      size="small"
                      icon="el-icon-edit"
                      v-if="permission.database_delete"
                      @click="generatorAddSQL()">生成添加字段SQL
            </el-button>
            <el-button type="warning"
                      size="small"
                      icon="el-icon-edit"
                      v-if="permission.database_delete"
                      @click="generatorUpdateSQL()">生成修改字段SQL
            </el-button>
            <el-button type="warning"
                      size="small"
                      icon="el-icon-edit"
                      v-if="permission.database_delete"
                      @click="generatorIndexSQL()">生成索引SQL
            </el-button>
            <el-button type="warning"
                      size="small"
                      icon="el-icon-edit"
                      v-if="permission.database_delete"
                      @click="handleGenerator()">生成代码
            </el-button>
             <el-button type="warning"
                      size="small"
                      icon="el-icon-edit"
                      v-if="permission.database_delete"
                      @click="generatorAddEntity()">生成添加字段实体
            </el-button>
          </template>
          
        </avue-crud>
        <div class="el-drawer__footer"> 
          <el-button size="small" icon="el-icon-close" @click="cancelDrawer">取 消</el-button>
        </div>
    </el-drawer>
    <!-- 
      sql代码对话框
     -->
    <el-dialog title="SQL预览" width="70%" :visible.sync="sqlDialogVisible">
      <el-input
        id="sqlText"
        type="textarea"
        :autosize="{ minRows: 5, maxRows: 20}"
        readonly='true'
        v-model="sqlText">
      </el-input>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" id="copyBtn" @click="copyClipboard($event)" data-clipboard-target="#sqlText">复制SQL</el-button>
        <el-button size="small" type="primary" @click="sqlDialogVisible = false">创建表</el-button>
        <el-button size="small" @click="sqlDialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 
      路径对话框
     -->
    <el-dialog title="创建路径脚本预览" :visible.sync="pathDialog">
      <el-input
        id="pathText"
        type="textarea"
        :autosize="{ minRows: 5, maxRows: 20}"
        readonly='true'
        v-model="pathText">
      </el-input>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" id="copyBtn" @click="copyClipboardPath($event)" data-clipboard-target="#pathText">复制脚本</el-button>
        <el-button size="small" @click="pathDialog = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 
      批量添加数据对话框
     -->
    <el-dialog  title="变量标准化" 
      width='70%' 
      top="6vh"
      :close-on-click-modal='false' 
      :visible.sync="batchAddColumnDialog"
      destroy-on-close='true'
      center
      >
      <el-row>
        <el-col :span="6">
          <el-input
            type="textarea"
            :autosize="{ minRows: 20, maxRows: 20}"
            placeholder="可直接从excel粘贴中文变量"
            v-model="importDataArea"
            @change='handleImport'
            >
          </el-input>
        </el-col>
        <el-col :span="1">
        </el-col>
        <el-col :span="17">
          <el-table
            :data="allFieldData"
            height="430"
            border
            v-loading="tabLoading"
            :row-class-name="tableRowClassName"
            style="width: 100%"
            >
            <el-table-column
              prop="oldColumnComment"
              label="字段中文"
              width="150">
            </el-table-column>
            <el-table-column
              prop="columnName"
              label="字段名字"
              width="200">
            </el-table-column>
            <el-table-column
              prop="dataTypeFmt"
              label="数据类型"
              width="200">
            </el-table-column>
            <el-table-column
              prop="columnFullName"
              label="全名">
            </el-table-column>
            <el-table-column
              fixed="right"
              label="状态操作"
              width="120">
              <template slot-scope="scope">
                <el-tag  v-if="scope.row.foundFlag == 'root' || scope.row.foundFlag == 'find'"  size="small">需加变量库</el-tag>
                <el-tag  v-if="scope.row.foundFlag == 'field'"  >已在变量库</el-tag>
                <el-tag  v-if="scope.row.foundFlag == 'lostRoot'"  type="warning">缺失词根</el-tag>
                <el-tag  v-if="scope.row.foundFlag == 'lostAttrRoot'"  type="danger">缺失定语&词根</el-tag>
                <el-tag  v-if="scope.row.foundFlag == 'lostAttr'" type="success">缺失定语</el-tag>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
      
      <div slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" id="copyBtn" @click="handleBatchImport($event)" >批量添加字段</el-button>
        <el-button size="small" @click="batchAddColumnDialog = false">取 消</el-button>
      </div>
    </el-dialog>
  </basic-container>
</template>

<script>
import {autoGetSysToolDictFieldList} from '@/api/tool/sysToolDictFieldApi';
import {exportSysToolColumnsExcel,saveOrUpdateSysToolColumns,saveOrUpdateSysToolColumnsList,saveSysToolColumns,deleteSysToolColumns,querySysToolColumns,querySysToolColumnsListPage,updateSysToolColumns,deleteSysToolColumnsList} from '@/api/tool/sysToolColumnsApi';
import {generatorCode,exportSysToolTablesExcel,saveSysToolTables,deleteSysToolTables,querySysToolTables,querySysToolTablesListPage,updateSysToolTables,deleteSysToolTablesList} from '@/api/tool/sysToolTablesApi';
import {mapGetters} from 'vuex';
import {reqCommonMsg} from '@/util/reqCommonMsg';
import {genSQL,genIndexSQL,genAddColumnSQL,genUpdateColumnSQL,genAddColumnEntity} from '@/util/genSQL';
import {filterFormat, copyToClipboard} from '@/util/util';
export default {
  data() {
    return {
      drawerTitle: '数据表定义',
      drawerDialog: false,
      sqlDialogVisible : false,
      pathDialog: false,
      sqlText : '',
      pathText : '',
      form: {},
      selectionList: [],
      loading: true, 
      showColumn: [],
      option: {
        labelPosition: 'right',
        labelSuffix: '：',
        labelWidth: 120,
        dialogTop: '50',
        indexFixed:true, 
        stripe:true,
        //height: 'auto',
        calcHeight: 120,
        searchShow: true,
        searchMenuSpan: 6,
        tip: false,
        border: true,
        index: true,
        selection: true,
        addBtn: true,
        viewBtn: true,
        cancelBtn: true,
        delBtn: false,
        printBtn:true,
        saveBtn: true,
        filterBtn:true,          
        menuWidth: 260,
        dialogMenuPosition: 'center',
        dialogDirection:'rtl',
        dialogType:'dialog',
        dialogFullscreen:false,
        dialogClickModal:false,
        dialogWidth: '70%',
        highlightCurrentRow:  true,
        column: [
          {
            label: '所属系统',
            prop: 'tableCatalog', 
            type: 'select', 
            value: 'common',
            rules: [{
              required: true,
              message: '请选择所属系统',
              trigger: 'blur'
            }],
            dicData:[
              {
                label:'公共平台',
                value:'common'
              },{
                label:'宙斯',
                value:'zeus'
              },{
                label:'雅典娜',
                value:'athena'
              } ]
          },
          {
            label: '表类型',
            prop: 'tableType', 
            type: 'select', 
            search: true,
            searchMmultiple:true,
            searchFilterable:true,
            value: 'sys',
            rules: [{
              required: true,
              message: '请选择表类型',
              trigger: 'blur'
            }],
            dicData:[
              {
                label:'业务表',
                value:'biz'
              },{
                label:'系统表',
                value:'sys'
              },{
                label:'工具表',
                value:'tool'
              } ]
          },
          {
            label: '数据库',
            prop: 'tableSchema',
            search: true, 
            type: 'select', 
            search: true,
            sortable: true,
            value: 'DOOL1001',
            width: '100',
            rules: [{
              required: true,
              message: '请选择表类型',
              trigger: 'blur'
            }],
            dicData:[
              {
                label:'公共平台',
                value:'DOOL1001'
              },
              {
                label:'宙斯系统',
                value:'DOOL1002'
              },{
                label:'雅典娜',
                value:'ATHE1002'
              }
            ] 
          },
          {
            label: '表名',
            prop: 'tableName',
            sortable: true,

            //filterMultiple: true,
            width:180,
            rules: [{
              required: false,
              message: '请输入表名',
              trigger: 'blur'
            }]
          },
          
          {
            label: '主键',
            prop: 'primaryKey', 
            rules: [{
              required: true,
              message: '请输入主键名',
              trigger: 'blur'
            }]
          },
          {
            label: '菜单编号',
            prop: 'menuNo', 
            width:180,
            rules: [{
              required: false,
              message: '请输入主键名',
              trigger: 'blur'
            }]
          },
          {
            label: '表说明', 
            prop: 'tableComment',
            search: true, 
            filterable:true,
            minWidth:200, 
            span:24
          },
        ],
        group: [
          {
            label: '工程信息',
            icon: 'el-icon-info',
            prop: '1587820852668_22220',
            column: [
              {
                label: '模块名英文',
                prop: 'moduleName', 
                value: 'serviceName',
                rules: [{
                  required: true,
                  message: '请输入模块名英文',
                  trigger: 'blur'
                }]
              },
              {
                label: '服务名中文',
                prop: 'serviceName', 
                rules: [{
                  required: true,
                  message: '请输入服务名中文',
                  trigger: 'blur'
                }]
              },
              {
                label: '工程名',
                prop: 'projectName', 
                span: 24,
                rules: [{
                  required: true,
                  message: '请输入工程名',
                  trigger: 'blur'
                }]
              },
              {
                label: '后端包名',
                prop: 'packageName', 
                rules: [{
                  required: true,
                  message: '请输入后端包名',
                  trigger: 'blur'
                }]
              },
              {
                label: '前后端标志',
                prop: 'backFrontFlag', 
                type: 'radio',
                value: '0',
                dicData:[
                  {
                    label:'前后+后端',
                    value:'0'
                  },{
                    label:'前端',
                    value:'1'
                  },{
                    label:'后端',
                    value:'2'
                  } ],
                rules: [{
                  required: true,
                  message: '请选择前后端标志',
                  trigger: 'blur'
                }]
              }, 
              {
                label: '后端路径',
                prop: 'backendPath', 
                span: 24,
                rules: [{
                  required: true,
                  message: '请输入后端路径',
                  trigger: 'blur'
                }]
              },
              {
                label: '前端路径',
                prop: 'frontendPath',
                span: 24, 
                rules: [{
                  required: true,
                  message: '请输入表前缀',
                  trigger: 'blur'
                }]
              },
            ]
          }
        ]
      },
      data: [],

      // 表字段定义区
      columnSelectionList: [],
      allFieldData:[],
      tabLoading: false,
      importDataArea: 'ID\n租户ID',
      batchAddColumnDialog: false,
      currentFieldRow:{},
      columnForm: {},
      columnOption:{
        keyId:'id',
        menuWidth: 150,
        height: 500,
        addBtn:false,
        editBtn:false,
        addRowBtn:false,
        cellBtn:true,
        sortable:true,
        indexFixed:true, 
        index: true,
        border: true,
        highlightCurrentRow:  true,
        stripe:true,
        selection: true,

        column: [
          {
            label:'表名',
            minWidth: 150,
            prop: 'tableName'
          },
          {
            label:'字段中文名',
            width: 180,
            prop: 'columnComment',
            type: 'input',
            remote: true, 
            rules: [
              {
                required: true,
                message: '请选择中文名',
                trigger: 'blur'
              }
            ] 
          },
          {
            label:'字段变量名',
            prop: 'columnName',
            type: 'input',
            minWidth: 150, 
          },{
            label:'数据类型',
            prop: 'dataType', 
            type: 'select',
            width: 120, 
            dicData:[{
              label:'varchar',
              value: 'varchar'
            },{
              label:'int',
              value: 'int'
            },{
              label:'char',
              value: 'char'
            },{
              label:'decimal',
              value: 'decimal'
            },{
              label:'datetime',
              value: 'datetime'
            },{
              label:'bigint',
              value: 'bigint'
            },{
              label:'text',
              value: 'text'
            }]
          },{
            label:'数据长度',
            width: 120,
            prop: 'length' 
          },{
            label:'小数长度',
            width: 120,
            prop: 'decimalLength' 
          },{
            label:'是否Key',
            prop: 'columnKey',
            type:'switch',
            value: 'false',
            cell: true
          },{
            label:'默认值',
            width: 150,
            cell: true,
            prop: 'value' 
          },{
            label:'是否不为空',
            prop: 'nullable',
            type:'switch',
            width: 100,
            value: 'true',
            cell: true
          }]
      },
      columnData:[],
      
      // 请求参数区
      reqParams: { 
        singleBody: {},
        listBody: [{}],
        sqlCondition:[],
        orderRule: [],
        currentPage: 1,
        pageSize: 10
      },
      commonData: null,
      conditions: [],
      orderRules: [],
      singleBody: {},
      currentRow: {},
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      columnPage: {
        pageSize: 100,
        currentPage: 1,
        total: 0
      }
    };
  },
  computed: {
    ...mapGetters(['permission','userInfo']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.database_add, false),
        viewBtn: this.vaildData(this.permission.database_view, false),
        delBtn: this.vaildData(this.permission.database_delete, false),
        editBtn: this.vaildData(this.permission.database_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push({id : ele.id});
      });
      return ids;
    } 
  },
  methods: { 
    
    //加载列表数据
    onLoad(page) {
      this.loading = true;
      this.reqParams =  {
        singleBody: this.singleBody,
        listBody: [{}],
        sqlCondition: this.conditions,
        orderRule: this.orderRules,
        currentPage: page.currentPage, 
        pageSize: page.pageSize
      }
      //console1.log('reqParams = ',this.reqParams)
      this.commonData = reqCommonMsg(this.reqParams)
      querySysToolTablesListPage(this.commonData).then(res => {
        const data = res.data.body;
        this.page.total = data.total;
        this.data = data.listBody;
        this.data.forEach((item, index) => {
          if(item.index1 != '')
          {
            this.data[index].index1 = JSON.parse(item.index1);
          }
        });
        this.loading = false;
        this.selectionClear();
      }, error => {
        this.loading = false; 
      });
    },
    rowSave(row, done, loading) {
      this.reqParams.singleBody = row;
      this.commonData = reqCommonMsg(this.reqParams)
      saveSysToolTables(this.commonData).then(() => {
        done();
        this.singleBody={};
        this.onLoad(this.page);
        this.$message({
          customClass:'zZindex',
          type: 'success',
          message: '操作成功!'
        });
      }, error => {
        //console1.log(error);
        loading();
      });         
      //console1.log("row = ",row ,loading)
    },
    rowUpdate(row, index, done, loading) { 
      this.reqParams.singleBody = row;
      this.commonData = reqCommonMsg(this.reqParams)
      updateSysToolTables(this.commonData).then(() => {
        done();
        this.singleBody={};
        this.onLoad(this.page);
        this.$message({
          customClass:'zZindex',
          type: 'success',
          message: '操作成功!'
        });
      }, error => {
        //console1.log(error);
        loading();
      });
      //console1.log('loading = ',loading)
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.reqParams.singleBody = row;
          this.commonData = reqCommonMsg(this.reqParams);
          return deleteSysToolTables(this.commonData);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            customClass:'zZindex',
            type: 'success',
            message: '操作成功!'
          });
        }).catch(() => {});
    },
    /**
     * 双击打开详细窗口
     */
    handleRowDBLClick (row, event) {
      this.$refs.crud.rowView(row,row.$index);
    },
    searchReset() {
      this.conditions =[];
      this.singleBody = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.singleBody = params
      this.page.currentPage = 1;
      this.onLoad(this.page);
      done();
    },
    refreshChange(){
      this.singleBody = {};
      this.onLoad(this.page);
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.reqParams.listBody = this.ids;
          this.commonData = reqCommonMsg(this.reqParams);
          return deleteSysToolTablesList(this.commonData);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            customClass:'zZindex',
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        }).catch(() => {});
    },
    /**
     * 拷贝记录
     */
    handleCopy(row){
      this.$confirm('确定复制数据?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.loading=true;
          let copyValue=row;
          copyValue.id='0';
          copyValue.dataSign='0'
          copyValue.tableName='拷贝 '+ copyValue.tableName; 
          this.reqParams.singleBody = copyValue;
          this.commonData = reqCommonMsg(this.reqParams)
          saveSysToolTables(this.commonData).then(() => {
            this.singleBody={};
            this.onLoad(this.page);
            this.$message({
              customClass:'zZindex',
              type: 'success',
              message: '操作成功!'
            });
            this.loading=false;
          }, error => {
            //console1.log(error);
            this.loading=false;
          });
        }).catch(() => {});
    },
      
    beforeOpen(done, type) {
      this.reqParams =  {
        singleBody: {
          id:this.form.id
        }
      }
      let commonData = reqCommonMsg(this.reqParams)
      if (['edit', 'view'].includes(type)) {
        querySysToolTables(commonData).then(res => {
          if(res.data.body.singleBody.index1 != '')
          {
            res.data.body.singleBody.index1 = JSON.parse(res.data.body.singleBody.index1);
          } 
          this.form = res.data.body.singleBody;
        });
      }
      done();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    filterChange(result) {
      this.page.currentPage = 1;
      this.conditions = filterFormat(result)
      this.onLoad(this.page);
    },
    sortChange(val){
      this.singleBody = {};
      this.orderRules=[val]
      this.onLoad(this.page);
    },
    /**
     * 以下处理数据表字段配置
     */ 
    // 打开表字段弹框
    handleOpenColumn(row){
      this.currentRow = row;
      this.drawerDialog = true; 
      this.drawerTitle = '数据表定义('+row.tableName+')',
      this.cloumnOnLoad();
    },

    cloumnOnLoad(page) { 
      const loading = this.$loading({
        lock: true,
        text: '数据加载中...',
        spinner: 'el-icon-loading',
      });
      this.singleBody={
        tableName: this.currentRow.tableName
      }
      this.orderRules={
        prop: 'ordinalPosition',
        order: 'ascending'  //descending
      }
      this.reqParams =  {
        singleBody: this.singleBody,
        listBody: [{}],
        sqlCondition: this.conditions,
        orderRule: this.orderRules,
        currentPage: this.columnPage.currentPage, 
        pageSize: this.columnPage.pageSize,
        total: 0
      }
      this.commonData = reqCommonMsg(this.reqParams)
      querySysToolColumnsListPage(this.commonData).then(res => {
        const data = res.data.body;
        this.columnPage.total = data.total;
        this.columnData = data.listBody;  
        this.columnSelectionClear();
        loading.close();
      }, error => {
        loading.close();
      });
    },
    cloumnRefreshChange(){ 
      this.cloumnOnLoad();
    },

    
    cloumnAddUpdate(form,index,done,loading){
      loading();
      this.reqParams.singleBody = form;
      if(!this.reqParams.singleBody.id)
      {
        this.reqParams.singleBody.id='0'
      }
      this.commonData = reqCommonMsg(this.reqParams)
      saveOrUpdateSysToolColumns(this.commonData).then(() => {
        done();
        this.cloumnOnLoad();
        this.$message({
          customClass:'zZindex',
          type: 'success',
          message: '保存成功!'
        });
      }, error => {
        //console1.log(error);
        loading();
      });
      //console1.log('loading = ',loading)
    },
    
    cloumnRowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.reqParams.singleBody = row;
          this.commonData = reqCommonMsg(this.reqParams);
          return deleteSysToolColumns(this.commonData);
        })
        .then(() => {
          this.cloumnOnLoad();
          this.$message({
            customClass:'zZindex',
            type: 'success',
            message: '操作成功!'
          });
        }).catch(() => {});
    },
    cloumnSaveOrUpdate(){
      // 整理顺序
      this.columnData.forEach((item, index) => {
        this.columnData[index].ordinalPosition = index;
      }); 
      this.reqParams.listBody = this.columnData;
      this.commonData = reqCommonMsg(this.reqParams)
      saveOrUpdateSysToolColumnsList(this.commonData).then(() => {
        this.cloumnOnLoad();
        this.$message({
          customClass:'zZindex',
          type: 'success',
          message: '保存成功!'
        });
      }, error => {
        //console1.log(error);
      });
      //console1.log('this.columnData = ',JSON.stringify(this.columnData))
    },
    /**
     * 批量编辑字段
     */
    cloumnBatchEdit(){
      this.columnData.forEach((item, index) => {
        this.columnData[index].$cellEdit = true; 
      }); 
    },
    /**
     * 生成代码
     */
    handleGenerator() { 
      this.$confirm('生成代码会覆盖旧代码，请确认数据表基础信息已配置正确，确定要重新生成?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.reqParams.singleBody = this.currentRow;
        this.commonData = reqCommonMsg(this.reqParams)
        generatorCode(this.commonData).then(() => {
          this.$message({
            customClass:'zZindex',
            type: 'success',
            message: '操作成功!'
          });
        }, error => {
          //console1.log(error);
        });  
      })       
    },
    /**
     * 字段选择
     */
    columnSelectionChange(list) {
      this.columnSelectionList = list;
    },
    columnSelectionClear() {
      this.columnSelectionList = [];
      this.$refs.columnCrud.toggleSelection();
    },
    /**
     * 生成SQL语句
     */
    generatorSQL(){
      this.columnData.forEach((element,index) => {
        if(element.columnName.trim() == ''){
          this.$message({
            customClass:'zZindex',
            type: 'warning',
            message: '第'+(index+1)+'行字段变量不完整!'
          });
          throw new Error('第'+(index+1)+'行字段变量不完整!——人工异常');
        }
        else if(element.columnComment.trim() == ''){
          this.$message({
            customClass:'zZindex',
            type: 'warning',
            message: '第'+(index+1)+'行字段名字不完整!'
          });
          throw new Error('第'+(index+1)+'行字段名字不完整!——人工异常');
        }
      });
      this.sqlDialogVisible=true;
      this.sqlText = genSQL(this.currentRow,this.columnData);
      //console1.log('==generatorSQL =',this.sqlText);
    },

    /**
     * 生成添加字段SQL语句
     */
    generatorAddSQL(){
      if (this.columnSelectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.sqlDialogVisible=true;
      this.sqlText = genAddColumnSQL(this.currentRow,this.columnSelectionList)
      //console1.log(' == generatorAddSQL == ',this.sqlText)
    },
    /**
     * 生成添加实体语句
     */
    generatorAddEntity(){
      if (this.columnSelectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.sqlDialogVisible=true;
      this.sqlText = genAddColumnEntity(this.currentRow,this.columnSelectionList)
      //console1.log(' == generatorAddSQL == ',this.sqlText)
    },

    /**
     * 生成修改字段SQL语句
     */
    generatorUpdateSQL(){
      if (this.columnSelectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.sqlDialogVisible=true;
      this.sqlText = genUpdateColumnSQL(this.currentRow,this.columnSelectionList)
      //console1.log(' == generatorUpdateSQL == ',this.sqlText)
    },
    /**
     * 生成索引SQL语句
     */
    generatorIndexSQL(){
      if (this.columnSelectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.sqlDialogVisible=true;
      this.sqlText = genIndexSQL(this.currentRow,this.columnSelectionList)
      //console1.log(' == generatorIndexSQL == ',this.sqlText)
    }, 
    /**
     * 若不能自动生成目录，可以做拷贝创建目录脚本
     */
    openPathDialog(){
      this.pathDialog = true;
      var outPath = '';
      var packagePath = this.currentRow.packageName.replace(/\./g, '/')
      outPath += 'mkdir -p ' + this.currentRow.backendPath+'/'+this.currentRow.projectName+'/src/main/java/'+packagePath+'/entity \n';
		  outPath += 'mkdir -p ' + this.currentRow.backendPath+'/'+this.currentRow.projectName+'/src/main/java/'+packagePath+'/controller \n';
      outPath += 'mkdir -p ' + this.currentRow.backendPath+'/'+this.currentRow.projectName+'/src/main/java/'+packagePath+'/mapper \n';
    	outPath += 'mkdir -p ' + this.currentRow.backendPath+'/'+this.currentRow.projectName+'/src/main/java/'+packagePath+'/service/impl \n';
      outPath += 'mkdir -p ' + this.currentRow.backendPath+'/'+this.currentRow.projectName+'/src/main/resources \n';
      outPath += 'mkdir -p ' + this.currentRow.frontendPath+'/views/'+this.currentRow.moduleName+' \n';
      outPath += 'mkdir -p ' + this.currentRow.frontendPath+'/api/'+this.currentRow.moduleName+' \n';
      this.pathText = outPath;
    },
    
    copyClipboardPath(){  
      copyToClipboard(this.pathText,this);
    },
    /**
     * 拷贝到剪贴板
     */
    copyClipboard(){
      copyToClipboard(this.sqlText,this);  
    },
    /**
     * 添加一个字段
     */
    cloumnAddRow(row) {
      // this.$message.success('添加成功！')
      this.$refs.columnCrud.rowCellAdd({
        tableSchema: this.currentRow.tableSchema,
        tableName: this.currentRow.tableName,
        columnComment: row.columnComment || '',
        columnName: row.columnName || '',
        ordinalPosition: 100,
        nullable: true,
        dataType: row.dataType || 'varchar',
        length: row.length || '100',
        decimalLength: row.decimalLength || '0',
        columnKey: false,
        type: 'input',
        search: false,
        searchMultiple: false,
        searchLabelWidth: 100,
        multiple: false,
        dicData: '[]',
        width: '0',
        span: '12',
        excel: true,
        sortable: false,
        required: false,
        showInForm: true,
        message: '请输入内容',
        hide: false,
        value: '',
        overHidden: true
      });
    },
    /**
     * 批量添加变量
     */
    cloumnBatchAdd(){
      this.batchAddColumnDialog = true;
    },
    /**
     * 标准化数据
     */
    handleImport() {
      this.tabLoading=true;
      var dataList = new Array();
      if(this.importDataArea){
        var lineList = this.importDataArea.split('\n')
        var indx = 0;
        lineList.forEach((element,index) => {
          if(element != null && element.trim() != ''){
            var fieldList = {
              comment:element,
            }
            dataList[indx] = fieldList
            indx++;
            //console1.log('fieldList = ',fieldList)
          }
        });
        //批量写入记录
        this.reqParams.listBody = dataList;
        this.commonData = reqCommonMsg(this.reqParams)
        autoGetSysToolDictFieldList(this.commonData).then(res => {
          this.tabLoading=false;
          this.allFieldData = res.data.body.listBody;
        }, error => {
          //console1.log(error);
          this.tabLoading=false;
        });      
        //console1.log('lineList=',dataList)
      }
      else{
        this.tabLoading=false;
        this.$message({
          customClass:'zZindex',
          type: 'warning',
          message: '数据为空或不正确!'
        });
      }
    },
    /**
     * 批量添加字段到字段列表
     */
    handleBatchImport() {
      if(this.allFieldData.length <=0){
        this.$message({
          customClass:'zZindex',
          type: 'warning',
          message: '字段列表为空!'
        }); 
        return false;
      }
      this.$confirm('确定要导入字段数据到字段列表?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.batchAddColumnDialog = false;
          this.tabLoading=true;
          this.allFieldData.forEach((element,index) => {
            this.cloumnAddRow(element);
          });
          this.tabLoading=false;
        })
        .then(() => { 
          this.$message({
            customClass:'zZindex',
            type: 'success',
            message: '操作成功!'
          }); 
        }).catch(() => {});
    },
    cancelDrawer() {
      this.drawerDialog = false;
    },
    closeDrawer(){
      this.singleBody.tableName = null
      this.columnData = [];
      this.orderRules = [];
    },
    /**
     * 导出Excel
     */
    exportExcel() {
      this.reqParams =  {
        singleBody: this.singleBody,
        listBody: [{}],
        sqlCondition: this.conditions,
        orderRule: this.orderRules,
        currentPage:1, 
        pageSize: 100
      }
      //console1.log('reqParams = ',this.reqParams)
      this.commonData = reqCommonMsg(this.reqParams)
      exportSysToolTablesExcel(this.commonData);
    },
    /**
     * 动态获取样式
     */
    tableRowClassName({row, rowIndex}) {
      if (row.foundFlag === 'field') {
        return 'in-field-row';
      } else if (row.foundFlag === 'root') {
        return 'in-root-row';
      }
      else {
        return '';
      } 
    }
  },
  
  created() {
    this.showColumn = this.$getStore({name:  this.userInfo.userId +'tableColumn'});
  },
  watch: {
    showColumn: {
      handler(newValue, oldValue) {
        this.$setStore({name:  this.userInfo.userId+'tableColumn', content: this.showColumn});
      },
      deep: true
      //this.$setStore({name: this.userInfo.userId +'tableColumn', content: this.showColumn});
    }
  }
};
</script>
<style>
  .el-table .in-field-row {
    background:lightgreen !important;
  }

  .el-table .in-root-row {
    background:powderblue !important;
  }
</style>

